package com.gc.flashview;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.FloatRange;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Interpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Scroller;

import com.bumptech.glide.Glide;
import com.gc.flashview.adapter.MZPagerAdapter;
import com.gc.flashview.effect.AccordionTransformer;
import com.gc.flashview.effect.CubeTransformer;
import com.gc.flashview.effect.DefaultTransformer;
import com.gc.flashview.effect.DepthPageTransformer;
import com.gc.flashview.effect.DepthScaleTransformer;
import com.gc.flashview.effect.InRightDownTransformer;
import com.gc.flashview.effect.InRightUpTransformer;
import com.gc.flashview.effect.RotateTransformer;
import com.gc.flashview.effect.ScaleTransformer;
import com.gc.flashview.effect.ZoomOutPageTransformer;
import com.gc.flashview.listener.OnItemClickListener;
import com.tentinet.flashviewproject.R;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * 访魅族轮播
 * <h3>Description</h3>
 * TODO
 * <h3>Author</h3> Louis
 * <h3>Date</h3> 2018/7/20 10:24
 * <h3>Copyright</h3> Copyright (c) 2018 Shenzhen ChinaSoft International Co., Ltd. Inc. All rights reserved.
 */
public class MZFlashView extends RelativeLayout implements ViewPager.OnPageChangeListener{

    /** 图片地址集合*/
    private List<String> imageUris;
    /** 图片集合用于暂时存储*/
    private ArrayList<ImageView> imageViewsList;
    /** 点集合用于暂时存储*/
    private ArrayList<ImageView> dotViewsList;
    /** 点容器*/
    private LinearLayout mLinearLayout;
    /** 图片容器*/
    private ViewPager mViewPager;
    /** 图片切换的动画效果*/
    private Effect effect;//
    /** 比率*/
    private float ratio = Float.NaN;
    /** page 间隔*/
    private int pageMargin = 0;

    private MZPagerAdapter pagerAdapter;

    /** 更新*/
    protected static final int MSG_UPDATE_IMAGE = 0x31;
    /** 保持*/
    protected static final int MSG_KEEP_SILENT = 0x32;

    protected static final int MSG_BREAK_SILENT = 0x33;

    protected static final int MSG_PAGE_CHANGED = 0x34;
    /** 停止自动滚动*/
    protected static final int MSG_STOP_SCROLL = 0x35;
    /** 延迟时间*/
    protected static final long MSG_DELAY = 2000;
    private int currentItem;
    /** 是否自动滚动 */
    private boolean isAuto = true;
    private int screenWidth;
    private int screenHeight;
    /** page 所占得屏宽 */
    private float mutiRatio = 1f;
    /** page 宽高比*/
    private float ratioHeightWidth = 0.7f;
//    private View viewPageParent;
    /** ViewPage默认高度 */
    private int defWidth;
    private int defHeight;


    private Handler mHandler = new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if (mHandler.hasMessages(MSG_UPDATE_IMAGE)){
                if (currentItem > 0){//
                    mHandler.removeMessages(MSG_UPDATE_IMAGE);
                }
            }
            switch (msg.what){
                case MSG_UPDATE_IMAGE:
                    if (isAuto){
                        currentItem ++;
                        mViewPager.setCurrentItem(currentItem);
                        mHandler.sendEmptyMessageDelayed(MSG_UPDATE_IMAGE, MSG_DELAY);
                    }
                    break;
                case MSG_KEEP_SILENT:
                    break;
                case MSG_BREAK_SILENT:
                    break;
                case MSG_PAGE_CHANGED:
                    currentItem = msg.arg1;
                    mHandler.sendEmptyMessageDelayed(MSG_UPDATE_IMAGE, MSG_DELAY);
                    break;
                case MSG_STOP_SCROLL:
                    if (mHandler.hasMessages(MSG_UPDATE_IMAGE)){
                        mHandler.removeMessages(MSG_UPDATE_IMAGE);
                    }
                    break;

            }
        }
    };



    public MZFlashView(@NonNull Context context) {
        this(context,null);
    }

    public MZFlashView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context,attrs,0);

    }

    public MZFlashView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray mTypedArray = context.obtainStyledAttributes(attrs, R.styleable.MZFlashView);
        effect = Effect.getEffect(mTypedArray.getInt(R.styleable.MZFlashView_MZEffect, 2));
        ratio = mTypedArray.getFloat(R.styleable.MZFlashView_ratio,Float.NaN);
        pageMargin = mTypedArray.getInt(R.styleable.MZFlashView_page_margin,0);
        init();
    }

    /**
     * 初始化
     *<h3>Description</h3>
     * TODO
     *<h3>Author</h3> Louis
     *<h3>Date</h3> 2018/7/20 10:27
     *<h3>Copyright</h3> Copyright (c)  Shenzhen ChinaSoft International Co., Ltd. Inc. All rights reserved.
     */
    @SuppressLint("ResourceType")
    private void init() {
        imageViewsList = new ArrayList<>();
        dotViewsList = new ArrayList<>();
        imageUris = new ArrayList<>();

        mLinearLayout = new LinearLayout(getContext());
        mViewPager = new ViewPager(getContext());
        screenWidth = getContext().getResources().getDisplayMetrics().widthPixels;
        screenHeight = getContext().getResources().getDisplayMetrics().heightPixels;
        mViewPager.setOffscreenPageLimit(3);
        mViewPager.setId(1);

        RelativeLayout.LayoutParams PageParams;
        ViewGroup.LayoutParams parentParams;

        if (ratio != Float.NaN){
            defWidth = (int) (screenWidth * ratio);
            defHeight = (int) (screenWidth * ratio * ratioHeightWidth);
            PageParams = new RelativeLayout.LayoutParams(defWidth, defHeight);
            parentParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,defHeight);
        }else {
            PageParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
            parentParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
        }

//        setLayoutParams(parentParams);

        setClipChildren(false);
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);

        layoutParams.addRule(ALIGN_PARENT_BOTTOM);
        layoutParams.addRule(CENTER_HORIZONTAL);
        layoutParams.addRule(ALIGN_PARENT_BOTTOM);
        PageParams.addRule(CENTER_HORIZONTAL);


        addView(mLinearLayout,layoutParams);
        addView(mViewPager,PageParams);

    }

    /**
     * 设置img地址
     *<h3>Description</h3>
     * TODO
     *<h3>Author</h3> Louis
     *<h3>Date</h3> 2018/7/20 10:49
     *<h3>Copyright</h3> Copyright (c)  Shenzhen ChinaSoft International Co., Ltd. Inc. All rights reserved.
     */
    public void setImageUris(List<String> imageUris){
        if (imageUris != null && !imageUris.isEmpty()){
            this.imageUris.clear();
            imageViewsList.clear();
            dotViewsList.clear();
            mLinearLayout.removeAllViews();
            this.imageUris.addAll(imageUris);
        }

        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        lp.setMargins(5, 0, 0, 0);

        for (int i = 0; i < imageUris.size(); i++) {

            ImageView imageView =  new ImageView(getContext());
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);// X和Y方向都填满

            ViewGroup.LayoutParams imgParam;

            if (ratio != Float.NaN){
                imgParam = new ViewGroup.LayoutParams(defWidth,defHeight);
            }else {
                imgParam = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT);
            }

            imageView.setLayoutParams(imgParam);

            Glide.with(getContext())
                    .load(this.imageUris.get(i))
                    .error(R.mipmap.ic_defaule_fail_bg)
                    .placeholder(R.mipmap.ic_defaule_fail_bg)
                    .into(imageView);

            ImageView viewDot = new ImageView(getContext());
            if (i == 0) {
                viewDot.setBackgroundResource(R.mipmap.dot_white);
            } else {
                viewDot.setBackgroundResource(R.mipmap.dot_light);
            }
            viewDot.setLayoutParams(lp);

            dotViewsList.add(viewDot);
            imageViewsList.add(imageView);
            mLinearLayout.addView(viewDot);
        }
        mViewPager.setFocusable(true);
        pagerAdapter = new MZPagerAdapter(imageViewsList);
        mViewPager.setAdapter(pagerAdapter);
        setEffect(effect);
        mViewPager.addOnPageChangeListener(this);
    }


    /**
     * 设置动画效果
     * <h3>Version</h3> 1.0
     * <h3>CreateTime</h3> 2016/1/7,18:04
     * <h3>UpdateTime</h3> 2016/1/7,18:04
     * <h3>CreateAuthor</h3> luzhenbang
     * <h3>UpdateAuthor</h3>
     * <h3>UpdateInfo</h3> (此处输入修改内容,若无修改可不写.)
     *
     * @param selectEffect
     */
    public void setEffect(Effect selectEffect) {
        switch (selectEffect.effect) {
            case 0://左右折叠效果
                mViewPager.setPageTransformer(true,new AccordionTransformer());
                break;
            case 1://立方体效果
                mViewPager.setPageTransformer(true,new CubeTransformer());
                break;
            case 2://默认效果
                mViewPager.setPageTransformer(true,new DefaultTransformer());
                break;
            case 3://深入浅出效果
                mViewPager.setPageTransformer(true,new DepthPageTransformer());
                break;
            case 4://右下角进入效果
                mViewPager.setPageTransformer(true,new InRightDownTransformer());
                break;
            case 5://右上角进入效果
                mViewPager.setPageTransformer(true,new InRightUpTransformer());
                break;
            case 6://旋转效果
                mViewPager.setPageTransformer(true,new RotateTransformer());
                break;
            case 7://淡入淡出效果
                mViewPager.setPageTransformer(true,new ZoomOutPageTransformer());
                break;
            case 8:
                mViewPager.setPageTransformer(true,new DepthScaleTransformer());
                break;
            case 9:
                mViewPager.setPageTransformer(true,new ScaleTransformer());
                break;
            default:
                break;
        }

        try {
            Field field = ViewPager.class.getDeclaredField("mScroller");
            field.setAccessible(true);
            FixedSpeedScroller scroller = new FixedSpeedScroller(mViewPager.getContext(), new AccelerateInterpolator());
            scroller.setmDuration(1000);
            field.set(mViewPager, scroller);
//            mViewPager.setCurrentItem(100 * imageViewsList.size());
            if (isAuto){
                mHandler.sendEmptyMessageDelayed(MSG_UPDATE_IMAGE, MSG_DELAY);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 切换轮播小点的显示
     *
     * <h3>Version</h3> 1.0
     * <h3>CreateTime</h3> 2016/1/7,16:34
     * <h3>UpdateTime</h3> 2016/1/7,16:34
     * <h3>CreateAuthor</h3> luzhenbang
     * <h3>UpdateAuthor</h3>
     * <h3>UpdateInfo</h3> (此处输入修改内容,若无修改可不写.)
     *
     * @param selectItems
     */
    private void setImageBackground(int selectItems) {
        for (int i = 0; i < dotViewsList.size(); i++) {
            if (i == selectItems % dotViewsList.size()) {
                dotViewsList.get(i).setBackgroundResource(R.mipmap.dot_white);
            } else {
                dotViewsList.get(i).setBackgroundResource(R.mipmap.dot_light);
            }
        }
    }



    /**
     *  测试是否循环轮播
     *  (此处输入方法执行任务.)
     * <h3>Version</h3> 1.0
     * <h3>CreateTime</h3> 2018/7/20,15:04
     * <h3>UpdateTime</h3> 2018/7/20,15:04
     * <h3>CreateAuthor</h3> Louis
     * <h3>UpdateAuthor</h3>
     * <h3>UpdateInfo</h3> (此处输入修改内容,若无修改可不写.)
     * @param loop
     */
    public void setLoop(boolean loop) {
        if (pagerAdapter != null){
            pagerAdapter.setLoop(loop);
        }
    }


    /**
     *  测试是否自动滚动
     *  (此处输入方法执行任务.)
     * <h3>Version</h3> 1.0
     * <h3>CreateTime</h3> 2018/7/20,15:04
     * <h3>UpdateTime</h3> 2018/7/20,15:04
     * <h3>CreateAuthor</h3> Louis
     * <h3>UpdateAuthor</h3>
     * <h3>UpdateInfo</h3> (此处输入修改内容,若无修改可不写.)
     * @param auto
     */
    public void setAuto(boolean auto) {
        isAuto = auto;
        mHandler.sendEmptyMessage(MSG_STOP_SCROLL);
    }


    public void setRatio(@FloatRange(from = 0,to = 1) float ratio) {
        this.ratio = ratio;
        if (imageViewsList != null && imageViewsList.size() > 0){
            for (ImageView view : imageViewsList) {
                defHeight = (int) (screenWidth * mutiRatio * this.ratio  * ratioHeightWidth);
                defWidth = (int) (screenWidth * mutiRatio * this.ratio);
                ViewGroup.LayoutParams imgParam = view.getLayoutParams();
                if (ratio != Float.NaN){
                    imgParam.width = defWidth;
                    imgParam.height = defHeight;
                }else {

                }
                view.setLayoutParams(imgParam);
            }
            //        //计算剩余的空间
            float pageMargin = (1 - ratio) * screenWidth;
            mViewPager.setPageMargin((int) -pageMargin);
        }
    }



    public void setMutiRatio(@FloatRange(from = 0,to = 1) float ratio){
        mutiRatio = ratio;
        ViewGroup.LayoutParams layoutParams = mViewPager.getLayoutParams();
        layoutParams.width = (int) (screenWidth * mutiRatio);
        layoutParams.height = (int) (screenWidth * mutiRatio * ratioHeightWidth);
        mViewPager.setLayoutParams(layoutParams);

        setRatio(this.ratio);
    }




    public void setPageMargin(int pageMargin) {
        this.pageMargin = pageMargin;
        mViewPager.setPageMargin(pageMargin);
    }


    public void setIndicatorVisiable(boolean isVisiable){
        if (isVisiable){
            mLinearLayout.setVisibility(VISIBLE);
        }else {
            mLinearLayout.setVisibility(INVISIBLE);
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        if (isAuto){
            mHandler.sendMessage(Message.obtain(mHandler,MSG_PAGE_CHANGED, position, 0));
        }
        setImageBackground(position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        switch (state){
            case ViewPager.SCROLL_STATE_IDLE://空闲状态
                if (isAuto){
                    mHandler.sendEmptyMessageDelayed(MSG_UPDATE_IMAGE, MSG_DELAY);
                }
                break;
            case ViewPager.SCROLL_STATE_DRAGGING://滚动状态
                mHandler.sendEmptyMessageDelayed(MSG_KEEP_SILENT,0);
                break;
        }
    }

    public void  setOnItemClickListener(OnItemClickListener listener){
        if (pagerAdapter != null){
            pagerAdapter.setOnItemClickListener(listener);
        }
    }

    public class FixedSpeedScroller extends Scroller {
        /** 动画持续时间*/
        private int mDuration = 1500;

        public FixedSpeedScroller(Context context) {
            super(context);
        }

        public FixedSpeedScroller(Context context, Interpolator interpolator) {
            super(context, interpolator);
        }

        @Override
        public void startScroll(int startX, int startY, int dx, int dy, int duration) {
            super.startScroll(startX, startY, dx, dy, mDuration);
        }

        @Override
        public void startScroll(int startX, int startY, int dx, int dy) {
            super.startScroll(startX, startY, dx, dy, mDuration);
        }

        public void setmDuration(int time) {
            mDuration = time;
        }

        public int getmDuration() {
            return mDuration;
        }
    }


    public enum Effect {

        AccordionTransformer(0),
        DefaultTransformer(1),
        CubeTransformer(2),
        DepthPageTransformer(3),
        InRightDownTransformer(4),
        InRightUpTransformer(5),
        RotateTransformer(6),
        ZoomOutPageTransformer(7),
        DepthScaleTransformer(8),
        ScaleTransformer(9);

        int effect ;

        Effect(int effect) {
            this.effect = effect;
        }

        static Effect getEffect(int effect){
            for (Effect value : values()) {
                if (effect == value.effect){
                    return value;
                }
            }
            return DepthPageTransformer;
        }


    }

}
